package com.usefullc.crawler.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.crawler.constants.CrawlerConstants;
import com.usefullc.crawler.selenium.CrawlerWebDriver;
import com.usefullc.crawler.selenium.CrawlerWebDriverBuilder3;
import com.usefullc.crawler.selenium.CrawlerWebDriverParam;
import com.usefullc.system.controller.BaseController;
import com.usefullc.system.controller.WebResultBuilder;
import com.usefullc.system.entity.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Sampson
 * @date: 2022-01-10 15:28
 */
@RestController
@RequestMapping(path = "/test/selenium/")
@Api( tags="测试操作管理")
public class TestSeleniumController extends BaseController {

    @Autowired
    private CrawlerWebDriverBuilder3 crawlerWebDriverBuilder;

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "测试webDriver", response = WebResult.class)
    @PostMapping(path = "testWebDriver", produces = "application/json")
    public WebResult testChrome(@RequestParam String reqType) {
//        if (StringUtils.isEmpty(reqType)) {
//            reqType = WebDriverTypeEnum.CHROME.getCode();
//        }
        CrawlerWebDriver crawlerWebDriver = null;
        long takeTime = 0L;
        try{
            long startTime = System.currentTimeMillis();
//            String url  ="https://www.csdn.net/";
            String url  ="https://www.baidu.com/";
            CrawlerWebDriverParam param = new CrawlerWebDriverParam();
//            param.setActiveInstanceId(activeInstance.getId());
//            param.setEnableProxy(template.getEnableProxy());
//            param.setEnableImage(template.getEnableImage());
//            param.setEnableJavascript(template.getEnableJavascript());
//            param.setEnableStyle(template.getEnableStyle());
//            param.setTimeRdMs(template.getRunRdMs());
            crawlerWebDriver = crawlerWebDriverBuilder.open(url,param);
            WebDriver webDriver = crawlerWebDriver.getWebDriver();
//        webDriver.get("https://www.csdn.net/");
//            Object result = crawlerWebDriverBuilder.executeScript(webDriver, "var nodeList = document.querySelector(\"#floor-nav_557 > div > div > div\").querySelectorAll(\"a[href]\");\n" +
//                    "var elements = Array.from(nodeList);\n" +
//                    "return elements.map(function(o){return o.href});");
//            logger.info("result={}",result);
            takeTime = System.currentTimeMillis() - startTime;
            logger.info("take time={}",takeTime);

            crawlerWebDriverBuilder.executeScript(webDriver,"window.open();");
////            Actions action= new Actions(webDriver);
//            webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.ALT ,"t");
//            action.keyDown(Keys.ALT).sendKeys("T").keyUp(Keys.ALT).build().perform();
//            webDriver.get("http://www.baidu.com");

        }catch (Exception e){
            logger.error("error",e);
        }finally {
            crawlerWebDriverBuilder.close(crawlerWebDriver);
        }
//        String pageSource = webDriver.getPageSource();
//        logger.info(pageSource);
//        webDriver.quit();
        return WebResultBuilder.successResult(takeTime);
    }


    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "测试webDriver", response = WebResult.class)
    @PostMapping(path = "testWebDriver2", produces = "application/json")
    public WebResult testChrome2(@RequestParam String reqType) {
//        if (StringUtils.isEmpty(reqType)) {
//            reqType = WebDriverTypeEnum.CHROME.getCode();
//        }
        CrawlerWebDriver crawlerWebDriver = null;
        long takeTime = 0L;
        try{
            long startTime = System.currentTimeMillis();
            String url  ="http://www.huilian.com:28082/test/selenium/proxy";
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_IMAGE,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_JAVASCRIPT,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_STYLE,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_PROXY,"true");
            paramMap.put(CrawlerConstants.CRAWL_RUN_RD_MS,"1-3");
            crawlerWebDriver = crawlerWebDriverBuilder.open(url,new CrawlerWebDriverParam());
            WebDriver webDriver = crawlerWebDriver.getWebDriver();
//        webDriver.get("https://www.csdn.net/");
//            Object result = crawlerWebDriverBuilder.executeScript(webDriver, "var nodeList = document.querySelector(\"#floor-nav_557 > div > div > div\").querySelectorAll(\"a[href]\");\n" +
//                    "var elements = Array.from(nodeList);\n" +
//                    "return elements.map(function(o){return o.href});");
//            logger.info("result={}",result);
            takeTime = System.currentTimeMillis() - startTime;
            logger.info("take time={}",takeTime);

//            crawlerWebDriverBuilder.executeScript(webDriver,"window.open();");
////            Actions action= new Actions(webDriver);
//            webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.ALT ,"t");
//            action.keyDown(Keys.ALT).sendKeys("T").keyUp(Keys.ALT).build().perform();
//            webDriver.get("http://www.baidu.com");

        }catch (Exception e){
            logger.error("error",e);
        }finally {
            crawlerWebDriverBuilder.close(crawlerWebDriver);
        }
//        String pageSource = webDriver.getPageSource();
//        logger.info(pageSource);
//        webDriver.quit();
        return WebResultBuilder.successResult(takeTime);
    }



    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "testJym", response = WebResult.class)
    @PostMapping(path = "testJym", produces = "application/json")
    public WebResult testJym(@RequestParam String reqType) {
//        if (StringUtils.isEmpty(reqType)) {
//            reqType = WebDriverTypeEnum.CHROME.getCode();
//        }
        CrawlerWebDriver crawlerWebDriver = null;
        long takeTime = 0L;
        try{
            long startTime = System.currentTimeMillis();
            String url  ="https://www.jiaoyimao.com/?spm=gcmall.pcgoodlistpage.0.0";
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_IMAGE,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_JAVASCRIPT,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_STYLE,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_PROXY,"true");
            paramMap.put(CrawlerConstants.CRAWL_RUN_RD_MS,"1-3");
            CrawlerWebDriverParam crawlerWebDriverParam = new CrawlerWebDriverParam();
            crawlerWebDriverParam.setWebDriverType("firefox");
            crawlerWebDriverParam.setEnableImage(YesNoEnum.YES.getCode());
            crawlerWebDriverParam.setEnableJavascript(YesNoEnum.YES.getCode());
            crawlerWebDriverParam.setEnableStyle(YesNoEnum.YES.getCode());
            crawlerWebDriverParam.setEnableProxy(YesNoEnum.NO.getCode());
            crawlerWebDriverParam.setTimeRdMs("1-3");
//            crawlerWebDriverParam.setActiveInstanceId(0L);


            while(true){
                crawlerWebDriverParam.setCookie("ctoken=GX6kacaGKoVoekLFyfwoGB82; ssids=5461676121004636; logTraceJymId=265d31b25f00-40f9-af20-f9df; session=4951676121004651-NaN; isg=BK2teNnSsutOE1YHzNIbgX5Kv08nCuHc8YI9cO-y4MSzZs0YtVsdrIg3ULqAffmU; tfstk=cVolBAGGZS1sqdkzlbZWjD5i6ydAZtQzNDo-0Kgk3euj3RnPiYbV7Q7vnSR6aw1..; l=fBTyKatqT8ZDUFa1BO5CFurza77OuIRV1kPzaNbMiIEGa61PTF1iINCeqz3J7dtfgTf0vetyqRXMndUp5WaLSAkDBeYICky0axJ9-etzRy1..; cna=sIFuHI/mcTkCASSdpiEPVvlI; xlly_s=1; track_id=gcmall_1676121018141_849b56c6-a084-4924-bf63-2e4f078a5f3f; _m_h5_tk=6b93a0a933bf19817824ea69b7e9c4a9_1676128219430; _m_h5_tk_enc=cecf1052add885fb0eace562acf023a6; Hm_lvt_47366dcc92e834539e7e9c3dcc2441de=1676121020; Hm_lpvt_47366dcc92e834539e7e9c3dcc2441de=1676121598");
                crawlerWebDriver = crawlerWebDriverBuilder.open(url,crawlerWebDriverParam);
                WebDriver webDriver = crawlerWebDriver.getWebDriver();
//        webDriver.get("https://www.csdn.net/");
//            Object result = crawlerWebDriverBuilder.executeScript(webDriver, "var nodeList = document.querySelector(\"#floor-nav_557 > div > div > div\").querySelectorAll(\"a[href]\");\n" +
//                    "var elements = Array.from(nodeList);\n" +
//                    "return elements.map(function(o){return o.href});");
//            logger.info("result={}",result);
                takeTime = System.currentTimeMillis() - startTime;
                logger.info("take time={}",takeTime);

                try{
                    //找到我们所要拖动的元素A
                    WebElement A = webDriver.findElement(By.cssSelector("#nc_1_n1z"));
                    if(A != null){
                        Actions action = new Actions(webDriver);
////鼠标拖动A向左移动530,之后释放鼠标
//            action.dragAndDropBy(A, -530, 0).perform();
// 鼠标拖动A向上移动100,向右移动570之后释放鼠标
                        action.dragAndDropBy(A, 350, 0).perform();

                    }
                }catch (Exception e){
                   e.printStackTrace();
                }finally {
                    crawlerWebDriverBuilder.close(crawlerWebDriver);
                }


            }


//            crawlerWebDriverBuilder.executeScript(webDriver,"window.open();");
////            Actions action= new Actions(webDriver);
//            webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.ALT ,"t");
//            action.keyDown(Keys.ALT).sendKeys("T").keyUp(Keys.ALT).build().perform();
//            webDriver.get("http://www.baidu.com");

        }catch (Exception e){
            logger.error("error",e);
        }finally {
            crawlerWebDriverBuilder.close(crawlerWebDriver);
        }
//        String pageSource = webDriver.getPageSource();
//        logger.info(pageSource);
//        webDriver.quit();
        return WebResultBuilder.successResult(takeTime);
    }


    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "testNew", response = WebResult.class)
    @PostMapping(path = "testNew", produces = "application/json")
    public WebResult testNew() {
//        if (StringUtils.isEmpty(reqType)) {
//            reqType = WebDriverTypeEnum.CHROME.getCode();
//        }
        CrawlerWebDriver crawlerWebDriver = null;
        long takeTime = 0L;
        try{
            long startTime = System.currentTimeMillis();
//            String url  ="https://www.iesdouyin.com/share/video/7198156274129816869/?region=CN&mid=7198156316668431160&u_code=14iakg8f1&did=MS4wLjABAAAANwkJuWIRFOzg5uCpDRpMj4OX-QryoDgn-yYlXQnRwQQ&iid=MS4wLjABAAAANwkJuWIRFOzg5uCpDRpMj4OX-QryoDgn-yYlXQnRwQQ&with_sec_did=1&titleType=title&from_ssr=1";
            String url  ="http://www.sh.sgcc.com.cn/html/main/col8/column_8_1.html";
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_IMAGE,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_JAVASCRIPT,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_STYLE,"true");
            paramMap.put(CrawlerConstants.CRAWL_ENABLE_PROXY,"true");
            paramMap.put(CrawlerConstants.CRAWL_RUN_RD_MS,"1-3");
            CrawlerWebDriverParam crawlerWebDriverParam = new CrawlerWebDriverParam();
//            crawlerWebDriverParam.setWebDriverType("firefox");
            crawlerWebDriverParam.setWebDriverType("chrome");
            crawlerWebDriverParam.setEnableImage(YesNoEnum.YES.getCode());
            crawlerWebDriverParam.setEnableJavascript(YesNoEnum.YES.getCode());
            crawlerWebDriverParam.setEnableStyle(YesNoEnum.YES.getCode());
            crawlerWebDriverParam.setEnableProxy(YesNoEnum.NO.getCode());
            crawlerWebDriverParam.setTimeRdMs("1-3");
//            crawlerWebDriverParam.setActiveInstanceId(0L);

            crawlerWebDriver = crawlerWebDriverBuilder.open(url,crawlerWebDriverParam);
            WebDriver webDriver = crawlerWebDriver.getWebDriver();
//        webDriver.get("https://www.csdn.net/");
//            Object result = crawlerWebDriverBuilder.executeScript(webDriver, "var nodeList = document.querySelector(\"#floor-nav_557 > div > div > div\").querySelectorAll(\"a[href]\");\n" +
//                    "var elements = Array.from(nodeList);\n" +
//                    "return elements.map(function(o){return o.href});");
//            logger.info("result={}",result);
            String pageSource = webDriver.getPageSource();
            logger.info(pageSource);
            takeTime = System.currentTimeMillis() - startTime;
            logger.info("take time={}",takeTime);

                } catch (Exception e) {
                    logger.error("error", e);
                } finally {
                    crawlerWebDriverBuilder.close(crawlerWebDriver);
                }
//        String pageSource = webDriver.getPageSource();
//        logger.info(pageSource);
//        webDriver.quit();
        return WebResultBuilder.successResult(takeTime);
    }

    @ApiOperationSupport(author = "Sampson@usefullc.com")
    @ApiOperation(value = "测试Proxy", response = WebResult.class)
    @GetMapping(path = "proxy", produces = "application/json")
    public WebResult proxy(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        logger.info("headerNames={}",headerNames);
        logger.info("request={}",request);
        logger.info("request={}",request.getRemoteAddr());
        return WebResultBuilder.successResult();
    }





}
